import router from './router'
import store from './store'
import { getToken } from './utils/auth'

const whiteList = ['/login', '/404', '/401']

router.beforeEach(async (to, from, next) => {
    if (getToken()) {
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            if (store.getters.roles.length === 0) {
                try {
                    const accessRoutes = await store.dispatch('generateRoutes');
                    for(let i =0;i<accessRoutes.length;i++) {
                        router.addRoute(accessRoutes[i])
                    }
                    // router.addRoutes(accessRoutes)
                    next({ ...to, replace: true })
                } catch (error) {
                    console.log("合并路由error:", error)
                    store.dispatch('fedLogOut').then(()=>{
                        next({  path: '/' })
                    }).catch(err => err);
                }
            } else {
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login`) // 否则全部重定向到登录页
            // NProgress.done()
        }
    }
})
